package com.wyp168.renrenfilm.core.service.impl;

import com.wyp168.renrenfilm.core.feign.RenrenFastFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyp168.common.utils.PageUtils;
import com.wyp168.common.utils.Query;

import com.wyp168.renrenfilm.core.dao.FilmLabelRelationDao;
import com.wyp168.renrenfilm.core.entity.FilmLabelRelationEntity;
import com.wyp168.renrenfilm.core.service.FilmLabelRelationService;
import org.springframework.transaction.annotation.Transactional;


@Service("filmLabelRelationService")
public class FilmLabelRelationServiceImpl extends ServiceImpl<FilmLabelRelationDao, FilmLabelRelationEntity> implements FilmLabelRelationService {

    @Autowired
    private RenrenFastFeign renrenFastFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FilmLabelRelationEntity> page = this.page(
                new Query<FilmLabelRelationEntity>().getPage(params),
                new QueryWrapper<FilmLabelRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void bindingLabel(String username, Long filmId, List<Long> labelIds) {
        //删除旧的关系
        QueryWrapper<FilmLabelRelationEntity> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("film_id", filmId);
        this.remove(deleteWrapper);

        //构建新关系集合，并批量添加到数据库
        List<FilmLabelRelationEntity> filmLabelRelationEntities = labelIds.stream().map(labelId -> {
            FilmLabelRelationEntity filmLabelRelationEntity = new FilmLabelRelationEntity();
            filmLabelRelationEntity.setFilmId(filmId);
            filmLabelRelationEntity.setLabelId(labelId);
            filmLabelRelationEntity.setCreatedBy(username);
            filmLabelRelationEntity.setModifiedBy(username);
            return filmLabelRelationEntity;
        }).collect(Collectors.toList());

        this.saveBatch(filmLabelRelationEntities);

    }
}